package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code29RemoveNthNodeFromEndOfList {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 双指针
        ListNode dummy = new ListNode(-1, head);
        ListNode first = head;
        ListNode second = dummy;

        for (int i = 0; i < n; i++) {
            first = first.next;
        }

        while (first != null) {
            first = first.next;
            second = second.next;
        }

        ListNode t = second.next;
        second.next = t.next;
        t.next = null;
        t = null;
        return dummy.next;
    }
}
